using System;
using System.Windows;
using AdRotatorXNA;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using AdRotator.Model;
using System.Diagnostics;

namespace AdRotatorExampleXNA
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
#if(WINDOWS_PHONE)

            Application.Current.UnhandledException += new EventHandler<ApplicationUnhandledExceptionEventArgs>(Current_UnhandledException);
#endif
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);

            // Extend battery life under lock.
            InactiveSleepTime = TimeSpan.FromSeconds(1);

            

            graphics.PreferredBackBufferWidth = 480;
            graphics.PreferredBackBufferHeight = 800;

            graphics.IsFullScreen = true;

            Window.OrientationChanged += new EventHandler<EventArgs>(Window_OrientationChanged);
            graphics.SupportedOrientations = DisplayOrientation.Portrait |
                DisplayOrientation.LandscapeLeft |
                DisplayOrientation.LandscapeRight;
        }

        protected override void OnActivated(object sender, EventArgs args)
        {
            try
            {
                LittleWatson.CheckForPreviousException("adrotator@xna-uk.net", "AdRotator XNA Example Error Report");
            }
            catch { } 
            base.OnActivated(sender, args);
        }

#if(WINDOWS_PHONE)
        void Current_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
            else
            {
                try
                {
                    LittleWatson.ReportException((Exception)e.ExceptionObject, "AdRotator XNA Error");
                }
                catch { }
            }
        }
#endif

        void Window_OrientationChanged(object sender, EventArgs e)
        {
            switch (Window.CurrentOrientation)
            {
                case DisplayOrientation.Portrait:
                    AdRotatorXNAComponent.Current.AdPosition = new Vector2(0, 0);
                    break;
                default:
                    AdRotatorXNAComponent.Current.AdPosition = new Vector2((GraphicsDevice.Viewport.Width / 2) - 240, 0);
                    break;
            }
            AdRotatorXNAComponent.Current.UpdateAdPostition();
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            AdRotatorXNAComponent.Initialize(this);

            //Optional Local Hard coded Ad Provider setings

            //AdRotatorXNAComponent.Current.PubCenterAppId = "test_client";
            //AdRotatorXNAComponent.Current.PubCenterAdUnitId = "Image480_80";

            //AdRotatorXNAComponent.Current.AdDuplexAppId = "0";

            //AdRotatorXNAComponent.Current.InneractiveAppId = "DavideCleopadre_ClockAlarmNightLight_WP7";

            //AdRotatorXNAComponent.Current.MobFoxAppId = "474b65a3575dcbc261090efb2b996301";
            //AdRotatorXNAComponent.Current.MobFoxIsTest = true;

            //Specify where you want the Ad to display (based on the top left corner of the Ad)
            AdRotatorXNAComponent.Current.AdPosition = new Vector2(0,720);

            //Optionally specify your own House Ad which will display if there is no network
            AdRotatorXNAComponent.Current.DefaultHouseAdImage = Content.Load<Texture2D>(@"AdRotatorDefaultAdImage");

            //Event handler to do something should the user click on your Default House Ad
            AdRotatorXNAComponent.Current.DefaultHouseAdClick += new AdRotatorXNAComponent.DefaultHouseAdClickEventHandler(Current_DefaultHouseAdClick);

            //Optionally specify the slide (popup) direction for the Ad
            AdRotatorXNAComponent.Current.SlidingAdDirection = SlideDirection.Bottom;

            //Optionally Set the local configuration file used to set the default Ad Locations
            AdRotatorXNAComponent.Current.DefaultSettingsFileUri = "defaultAdSettings.xml";

            //Optionally set a URL from where to pull the configuration file down remotely each time the game is run
            AdRotatorXNAComponent.Current.SettingsUrl = "http://adrotator.apphb.com/defaultAdSettingsXNA.xml";

            //Add the control to the XNA Component list which will display the ad
            //Note as this is XNA be sure to just to this for the game states you want it shown.
            Components.Add(AdRotatorXNAComponent.Current);

            //To disable AdRotator and all controls use the following setting
            //AdRotatorXNAComponent.Current.Enabled = false;
            AdRotatorXNAComponent.Current.Log += Current_Log;
            base.Initialize();
        }

        void Current_Log(string message)
        {
            Debug.WriteLine(message);
        }

        void Current_DefaultHouseAdClick()
        {
            try
            {
                MessageBox.Show("You clicked on my Ad, thanks very much");
            }
            catch { }
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }


    }
}
